require('./mongo/connect')
const ip = require('ip')
const express = require('express')
const app = express()

const allowOrigins = [
  'localhost',
  'hrhe.cn',
  'heny.vip',
  'weblearns.com',
  '127.0.0.1',
  '0.0.0.0',
]

app.use('/', (req, res, next) => {
  if (
    req.headers.origin &&
    allowOrigins.some((u) => req.headers.origin.includes(u))
  ) {
    res.header('Access-Control-Allow-Origin', req.headers.origin)
    res.header(
      'Access-Control-Allow-Headers',
      'Content-Type,Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild, appName'
    )
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE,OPTIONS')
  }
  next()
})

// 注意顺序  必须在msgRoutes之前挂载中间件
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

//引入路由
app.use('/msg', require('./routes/msg'))
app.use('/', require('./routes'))

// 创建连接socket.io
const server = require('http').Server(app)
const io = require('socket.io')(server, { cors: true })
require('./socket')(io)

// 开放uploads文件夹提供下载文件
app.use('/file', express.static('uploads'))

function getPort() {
  let configs = process.argv.slice(2)
  let portIndex = configs.findIndex((i) => String(i).includes('p'))
  return configs[portIndex + 1] || 8888
}
var port = process.env.PORT || 8888
server.listen(port, (_) => {
  console.log('You can now view chat in the browser.')
  console.log('   ')
  console.log(`Local:            http://localhost:${port}`)
  console.log(`On Your Network:  http://${ip.address()}:${port}`)
})

app.get('/', (req, res) => {
  res.send('服务启动成功')
})
